package servlet.user;

import bean.dto.Login;
import bean.pojo.User;
import bean.vo.UserVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import commons.baseServlet.BaseServlet;
import commons.r.R;
import service.LogService;
import service.UsersService;
import service.impl.LogServiceImpl;
import service.impl.UsersServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录
 */
@WebServlet(name = "LoginServlet", value ="/user/*")
public class LoginServlet extends BaseServlet {
    //保存登录用户token
    private static  String userToken=null;
    //保存登录的用户
    public static User loginUser=null;
    /**
     * 获取用户角色信息
     * @param request
     * @return
     */
    public R infoRole(HttpServletRequest request){
        //前端提交的是表单数据
        //axios 默认提交是 json数据
        String  token =request.getParameter("token");//token是json数据 name
        //  =request.getParameter就不能获取这数据因为数据请求流中
        System.out.println(token);
        //返回用户信息给前端 ServletContext
        User user =(User) getServletContext().getAttribute(token);
        System.out.println("infoRole:user:"+user);
        //通过用户信息查询用户角色
        UsersService usersService = new UsersServiceImpl();
        UserVo  vo=usersService.infoRole(user.getUserId());
        System.out.println("infoRole:UserVo:"+vo.toString());
        //结果集
        R r;
        //判断是否登录成功
        if(vo.getUserId()==null){
            r=R.error("没有登录");
        }else{
            r=R.ok(vo);
        }
        return r;
    }
    /**
     * 获取用户角色
     * @param request
     * @return
     */
    public R info(HttpServletRequest request){
        //前端提交的是表单数据
        //axios 默认提交是 json数据
        String  token =request.getParameter("token");//token是json数据 name
        //  =request.getParameter就不能获取这数据因为数据请求流中
        System.out.println(token);
        //返回用户信息给前端 ServletContext
        Object user = getServletContext().getAttribute(token);
        System.out.println("info:user:"+user);
        //结果集
        R r;
        //判断是否登录成功
        if(user==null){
            r=R.error("没有登录");
        }else{
            r=R.ok(user);
        }
        return r;
    }

    /**
     * 登录
     * @param request
     * @return
     * @throws IOException
     */
    public R login(HttpServletRequest request) throws IOException {
        //获取请求流 (因为前端传递的是   application/json 数据流  以json字符串格式体现
        BufferedReader reader=request.getReader();
        //数据
        String  data="";
        //接收数据
        data= reader.readLine();//"{'username':'1','passwor':'1'}"
        //把数据格式化(解析)
        Login login=  JSONObject.parseObject(data, Login.class);
        //实例业务对象
        UsersService  usersService=new UsersServiceImpl();
        //调用登录方法 返回用户的信息
        User user= usersService.login(login);
        loginUser=user;
        System.out.println(user.toString());
        if(user.getUserName()!=null){
            //插入日志
            Integer userId=user.getUserId();
            String userName=user.getUserName();
            LogService logService = new LogServiceImpl();
            logService.insert(userId,userName,"登录", LocalDateTime.now());
        }

        //结果集
        R r;
        //判断是否登录成功
        if(user==null){
            r=R.error("用户或者密码错误");
        }else{
            String  token=request.getSession().getId();
            Map<String,Object> resultData=new HashMap<>();
            resultData.put("token",token);
            userToken=token;
            r=R.ok(resultData);
            System.out.println(token);
            //哪些对象可以缓存数据? session  ServletContext  request
            // 以后是存在在Redis中现在只能把数据缓存在ServletContext对象中
            getServletContext().setAttribute(token,user);
            request.getSession().setAttribute("user",user);
            // r=R.ok()
            //        .addData("token",token)
            //         .addData("name","韩梅梅");//{token :235457567,name:韩梅梅}
        }

        return r;
    }

    /**
     * 登出
     * @param request
     * @throws IOException
     */
    public R logout(HttpServletRequest request) throws IOException {
        System.out.println("logout:userToken:"+userToken);
        getServletContext().removeAttribute(userToken);
        // 使当前会话失效（如果使用了HttpSession来管理会话相关信息）
        request.getSession().invalidate();
        User user = (User)getServletContext().getAttribute(userToken);
        System.out.println("logout:user:"+user);
        if(user==null){
            return R.ok();
        }
        return R.error();
    }

}
